<template>
  <!-- 卡片 -->
  <el-card class="box-card" style="padding: 10px 10px">
    <!-- 新增 -->
    <el-button
      type="primary"
      icon="Plus"
      style="margin-bottom: 20px"
      @click="insertBrand"
    >
      新增品牌
    </el-button>
    <!-- 表格 -->
    <el-table :data="brandList" border>
      <el-table-column type="index" label="序号" width="100px" />
      <el-table-column label="品牌名称">
        <template #="{ row, column, $index }">
          <span>{{ row.tmName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="品牌LOGO">
        <template #="{ row, column, $index }">
          <img :src="row.logoUrl" style="width: 50px; height: 50px" />
        </template>
      </el-table-column>
      <el-table-column label="品牌操作">
        <template #="{ row, column, $index }">
          <el-button
            type="primary"
            size="small"
            icon="Edit"
            @click="updateBrand(row)"
          >
            编辑
          </el-button>
          <el-popconfirm
            :title="`确定删除${row.tmName}?`"
            width="250px"
            @confirm="delBrand(row.id)"
          >
            <template #reference>
              <el-button type="primary" size="small" icon="Delete">
                删除
              </el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页器 -->
    <el-pagination
      style="margin-top: 20px"
      background
      v-model:current-page="page"
      v-model:page-size="pagesize"
      :page-sizes="[3, 5, 7, 9]"
      layout=" prev, pager, next, jumper,->,sizes,total "
      :total="total"
    />
  </el-card>
  <!-- dailog -->
  <el-dialog v-model="dialogFormVisible" title="新增品牌">
    <el-form
      style="width: 80%; padding: 20px 40px"
      ref="formRef"
      :model="brandFrom"
      :rules="rules"
    >
      <el-form-item label="品牌名称" label-width="100px" prop="tmName">
        <el-input v-model="brandFrom.tmName" />
      </el-form-item>
      <el-form-item label="品牌LOGO" label-width="100px" prop="logoUrl">
        <el-upload
          class="avatar-uploader"
          :on-progress="handleProgress"
          action="/api/admin/product/fileUpload"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
        >
          <img
            v-if="brandFrom.logoUrl"
            :src="brandFrom.logoUrl"
            class="avatar"
          />
          <el-icon v-else class="avatar-uploader-icon">
            <UploadFilled />
          </el-icon>
          <el-progress
            type="circle"
            :percentage="percentage"
            v-if="percentage != 100"
          ></el-progress>
        </el-upload>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="comfirm">确定</el-button>
      </span>
    </template>
  </el-dialog>
</template>
<script setup lang="ts">
import { ref, onMounted, watch, reactive, nextTick } from 'vue'
import {
  reqBaseTrademark,
  reqBaseTrademarkSave,
  reqBaseTrademarkUpdateDel,
} from '@/api/pro/brand.ts'
import { ElMessage } from 'element-plus'
const dialogFormVisible = ref<Boolean>(false)
const total = ref<number>(100)
const formRef = ref()
const percentage = ref(0)
const page = ref<number>(1)
const pagesize = ref<number>(3)
const brandList = ref([])
const brandFrom = reactive({
  id: '',
  tmName: '',
  logoUrl: '',
})
onMounted(() => {
  getBaseTrademark()
})
const getBaseTrademark = async () => {
  const res = await reqBaseTrademark(page.value, pagesize.value)
  if (res.code == 200) {
    brandList.value = res.data.records
    total.value = res.data.total
  }
}
watch(pagesize, () => {
  page.value = 1
  getBaseTrademark()
})
watch(page, () => {
  getBaseTrademark()
})
// 新增品牌的方法
const insertBrand = () => {
  brandFrom.id = ''
  percentage.value = 0
  brandFrom.tmName = ''
  brandFrom.logoUrl = ''
  dialogFormVisible.value = true
  nextTick(() => {
    formRef.value.clearValidate('logoUrl')
    formRef.value.clearValidate('tmName')
  })
}
// 修改品牌的方法
const updateBrand = (row) => {
  brandFrom.id = row.id
  brandFrom.tmName = row.tmName
  brandFrom.logoUrl = row.logoUrl
  dialogFormVisible.value = true
  nextTick(() => {
    formRef.value.clearValidate('logoUrl')
    formRef.value.clearValidate('tmName')
  })
}
const delBrand = async (id) => {
  const res = await reqBaseTrademarkUpdateDel(id)
  if (res.code == 200) {
    ElMessage.success('操作成功')
  } else {
    ElMessage.error('操作失败')
  }
  //重新刷新表格
  getBaseTrademark()
}
// 对话框确定方法
const comfirm = async () => {
  await formRef.value.validate()
  const res = await reqBaseTrademarkSave(brandFrom)
  if (res.code == 200) {
    ElMessage.success('操作成功')
  } else {
    ElMessage.error('操作失败')
  }
  dialogFormVisible.value = false
  //重新刷新表格
  getBaseTrademark()
}
// 限制文件上传
const beforeAvatarUpload = (rawFile) => {
  if (
    !(
      rawFile.type == 'image/jpeg' ||
      rawFile.type == 'image/png' ||
      rawFile.type == 'image/gif'
    )
  ) {
    ElMessage.error('文件格式必须为jpeg | png | gif')
    return false
  } else if (rawFile.size / 1024 / 1024 > 4) {
    ElMessage.error('文件大小需要少于 4MB!')
    return false
  }
  return true
}
// 文件上传成功的函数
const handleAvatarSuccess = (response, uploadFile) => {
  brandFrom.logoUrl = response.data
  formRef.value.clearValidate('logoUrl')
}
// 处理进度的函数
const handleProgress = (event, file, fileList) => {
  percentage.value = parseInt(((event.loaded / event.total) * 100).toFixed(0))
}

const validatetmName = (rule, value, callback) => {
  if (value.trim().length >= 2) {
    callback()
  } else {
    callback(new Error('品牌名大于2位'))
  }
}
const validatelogoUrl = (rule, value, callback) => {
  if (value) {
    callback()
  } else {
    callback(new Error('图片logo不能为空'))
  }
}
// 表单校验
const rules = reactive({
  logoUrl: [{ required: true, validator: validatelogoUrl }],
  tmName: [{ required: true, trigger: 'blur', validator: validatetmName }],
})
</script>

<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px solid var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
